package com.dhl.fin.api.service;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.dhl.fin.api.common.dto.ApiResponse;
import com.dhl.fin.api.common.exception.BusinessException;
import com.dhl.fin.api.common.service.ExceptionRecordService;
import com.dhl.fin.api.common.util.DateUtil;
import com.dhl.fin.api.common.util.JsonUtil;
import com.dhl.fin.api.common.util.MapUtil;
import com.dhl.fin.api.constant.ExceptionCodeConstant;
import com.dhl.fin.api.dto.TipMessageDTO;
import com.dhl.fin.api.dto.WeChatLoginReqDTO;
import com.dhl.fin.api.dto.WeChatMessageBodyReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * @author CuiJianbo
 * @since 2025/5/22
 */
@Slf4j
@Service
public class AbilityServiceCenterService {

    @Value("${custom.ascUrl}/wechat/getToken")
    private String tokenUrl;

    @Value("${custom.ascUrl}/wechat/miniProgramSendMsg")
    private String sendTemplateMsgUrl;

    @Value("${custom.ascUrl}/wechat/login")
    private String loginUrl;

    @Value("${custom.appId}")
    private String remindAppId;

    @Value("${custom.secret}")
    private String remindSecret;

    @Value("${custom.serviceAppId}")
    private String appId;

    @Value("${custom.serviceAppSecret}")
    private String secret;

    @Value("${custom.templateId}")
    private String templateId;

    @Value("${custom.miniProgramHomePage}")
    private String miniProgramHomePage;

    @Autowired
    private ExceptionRecordService exceptionRecordService;


    public String login(WeChatLoginReqDTO weChatLoginReqDTO) {
        //获取app对应的token
        String respJsonData = HttpRequest.post(loginUrl)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(JsonUtil.objectToString(weChatLoginReqDTO))
                .execute()
                .body();
        ApiResponse<Map> response = JsonUtil.parseToJavaBean(respJsonData, ApiResponse.class);
        if (response.getCode() == 0) {
            return response.getData().get("openId").toString();
        } else {
            log.error("登录失败：{}", response.getMsg());
            throw new BusinessException("登录失败");
        }
    }


    /**
     * 通过服务号给用户发送订阅消息
     */
    public void sendSubscribeMsgServer(TipMessageDTO tipMessageDTO) {
        Map<String, Object> params = MapUtil.builder()
                .add("secret", secret)
                .add("appid", appId)
                .build();

        //获取app对应的token
        String tokenResp = HttpUtil.get(tokenUrl, params);
        log.info("tokenResp: {}", tokenResp);
        String token = null;
        ApiResponse response = JsonUtil.parseToJavaBean(tokenResp, ApiResponse.class);
        if (response.getCode() == 0) {
            token = response.getData().toString();
        } else {
            log.error("获取token失败：{}", JsonUtil.objectToString(response));
            throw new BusinessException("获取token失败");
        }

        Map data = MapUtil.builder()
                .add("thing17", MapUtil.builder().add("value", tipMessageDTO.getRemindName()).build())
                .add("time15", MapUtil.builder().add("value", DateUtil.getFullTime(tipMessageDTO.getRemindDateTime())).build())
                .build();
        WeChatMessageBodyReqDTO weChatMessageBodyReqDTO = new WeChatMessageBodyReqDTO();
        weChatMessageBodyReqDTO.setTouser(tipMessageDTO.getOpenId());
        weChatMessageBodyReqDTO.setAccess_token(token);
        weChatMessageBodyReqDTO.setData(JsonUtil.objectToString(data));
        weChatMessageBodyReqDTO.setMiniprogram("{\n" +
                "             \"appid\":\"" + remindAppId + "\",\n" +
                "             \"pagepath\":\"/pages/remind/remind\"\n" +
                "           }");
        //给微信用户发送提醒消息
        String message = JsonUtil.objectToString(weChatMessageBodyReqDTO);
        String respJsonData = HttpRequest.post(sendTemplateMsgUrl)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(message)
                .execute()
                .body();
        response = JsonUtil.parseToJavaBean(respJsonData, ApiResponse.class);
        if (response.getCode() != 0) {
            log.error("给微信用户发送提醒消息失败：{}, 请求参数:{}", response.getMsg(), data);
            throw new BusinessException("给微信用户发送提醒消息失败");
        }
        log.info("已发送消息:{}", message);

    }

    /**
     * 通过小程序给用户发送订阅消息
     */
    public void sendSubscribeMsgMiniProgram(TipMessageDTO tipMessageDTO) {
        Map<String, Object> params = MapUtil.builder()
                .add("secret", remindSecret)
                .add("appid", remindAppId)
                .build();

        //获取app对应的token
        String tokenResp;
        try {
            tokenResp = HttpUtil.get(tokenUrl, params);
        } catch (Exception e) {
            log.error("请求AbilityCenter失败", e);
            exceptionRecordService.addRecordLog(ExceptionCodeConstant.CODE_30000, "请求AbilityCenter失败:" + e.getMessage(), JsonUtil.objectToString(params));
            throw new BusinessException("请求AbilityCenter失败");
        }
        log.info("tokenResp: {}", tokenResp);
        String token = null;
        ApiResponse response = JsonUtil.parseToJavaBean(tokenResp, ApiResponse.class);
        if (response.getCode() == 0) {
            token = response.getData().toString();
        } else {
            log.error("获取token失败：{}", JsonUtil.objectToString(response));
            throw new BusinessException("获取token失败");
        }

        Map data = MapUtil.builder()
                .add("thing26", MapUtil.builder().add("value", tipMessageDTO.getRemindName()).build())
                .add("thing15", MapUtil.builder().add("value", tipMessageDTO.getRemindType()).build())
                .add("thing4", MapUtil.builder().add("value", tipMessageDTO.getRemindDescription()).build())
                .add("short_thing20", MapUtil.builder().add("value", tipMessageDTO.getRemainTime()).build())
                .add("short_thing24", MapUtil.builder().add("value", tipMessageDTO.getRemindWayType()).build())
                .build();
        WeChatMessageBodyReqDTO weChatMessageBodyReqDTO = new WeChatMessageBodyReqDTO();
        weChatMessageBodyReqDTO.setTouser(tipMessageDTO.getOpenId());
        weChatMessageBodyReqDTO.setAccess_token(token);
        weChatMessageBodyReqDTO.setTemplate_id(templateId);
        weChatMessageBodyReqDTO.setPage(miniProgramHomePage);
        weChatMessageBodyReqDTO.setData(JsonUtil.objectToString(data));
        //给微信用户发送提醒消息
        String respJsonData = HttpRequest.post(sendTemplateMsgUrl)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(JsonUtil.objectToString(weChatMessageBodyReqDTO))
                .execute()
                .body();
        try {
            response = JsonUtil.parseToJavaBean(respJsonData, ApiResponse.class);
        } catch (Exception e) {
            log.error("服务器返回数据无法解析：{}，请求参数:{}", response.getMsg(), data);
            exceptionRecordService.addRecordLog(ExceptionCodeConstant.CODE_30002, e.getMessage(), JsonUtil.objectToString(tipMessageDTO));
            throw new BusinessException("服务器返回数据无法解析");
        }
        if (response.getCode() != 0) {
            log.error("给微信用户发送提醒消息失败：{}，请求参数:{}", response.getMsg(), data);
            exceptionRecordService.addRecordLog(ExceptionCodeConstant.CODE_30001, response.getMsg(), JsonUtil.objectToString(tipMessageDTO));
            throw new BusinessException("给微信用户发送提醒消息失败");
        }

    }

}
